<template>
  <view class="uqrcode-uni" :style="{ width: size + 'rpx', height: size + 'rpx' }">
    <canvas 
      type="2d"
      :id="canvasId" 
      :canvas-id="canvasId"
      :style="{ 
        width: size + 'rpx', 
        height: size + 'rpx'
      }"
      @click="handleClick"
    ></canvas>
  </view>
</template>

<script>
import UQRCode from 'uqrcodejs'

export default {
  name: 'uqrcode-uni',
  props: {
    // 二维码内容
    value: {
      type: String,
      default: ''
    },
    // 二维码尺寸 (rpx)
    size: {
      type: [String, Number],
      default: 200
    },
    // 是否隐藏
    hide: {
      type: Boolean,
      default: false
    },
    // 是否加载中
    loading: {
      type: Boolean,
      default: false
    },
    // 背景色
    backgroundColor: {
      type: String,
      default: '#ffffff'
    },
    // 前景色
    foregroundColor: {
      type: String,
      default: '#000000'
    },
    // 边距
    margin: {
      type: Number,
      default: 10
    },
    // 是否自动生成
    auto: {
      type: Boolean,
      default: true
    },
    // 是否初始化后立即生成
    start: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      canvasId: '',
      qrcode: null,
      generated: false
    }
  },
  computed: {
    canvasSize() {
      return Number(this.size)
    }
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal && this.auto && this.generated) {
          console.log('value changed:', newVal)
          this.make()
        }
      },
      immediate: false
    }
  },
  mounted() {
    this.canvasId = 'uqrcode-' + Date.now() + '-' + Math.random().toString(36).substring(2, 7)
    console.log('uqrcode-uni mounted, canvasId:', this.canvasId)
    
    if (this.start && this.value) {
      this.$nextTick(() => {
        setTimeout(() => {
          this.make()
        }, 100)
      })
    }
  },
  methods: {
    // 生成二维码
    make() {
      if (!this.value) {
        console.warn('二维码内容为空')
        return
      }
      
      console.log('开始生成二维码:', this.value)
      this.generated = false
      
      this.$nextTick(() => {
        setTimeout(() => {
          this.generateQRCode()
        }, 150)
      })
    },
    
    // 重新生成二维码
    remake() {
      this.make()
    },
    
    // 生成二维码核心逻辑
    async generateQRCode() {
      try {
        // 创建uQRCode实例
        const qr = new UQRCode()
        
        // 设置二维码内容
        qr.data = this.value
        
        // 设置二维码大小 (转换rpx到px)
        const systemInfo = uni.getSystemInfoSync()
        const screenWidth = systemInfo.screenWidth || 375
        const pxSize = (this.canvasSize * screenWidth) / 750
        qr.size = Math.floor(pxSize)
        
        // 设置样式选项
        qr.options = {
          margin: this.margin,
          backgroundColor: this.backgroundColor,
          foregroundColor: this.foregroundColor
        }
        
        console.log('二维码配置:', {
          data: qr.data,
          size: qr.size,
          canvasId: this.canvasId
        })
        
        // 调用制作二维码方法
        qr.make()
        
        // 获取canvas上下文 (Canvas 2D)
        const query = uni.createSelectorQuery().in(this)
        query.select(`#${this.canvasId}`)
          .fields({ node: true, size: true })
          .exec((res) => {
            if (res[0] && res[0].node) {
              const canvas = res[0].node
              const ctx = canvas.getContext('2d')
              
              // 设置canvas实际尺寸
              const dpr = uni.getSystemInfoSync().pixelRatio || 2
              canvas.width = qr.size * dpr
              canvas.height = qr.size * dpr
              ctx.scale(dpr, dpr)
              
              // 设置uQRCode实例的canvas上下文
              qr.canvasContext = ctx
              
              // 调用绘制方法将二维码图案绘制到canvas上
              qr.drawCanvas()
              
              console.log('二维码绘制完成')
              this.generated = true
              this.qrcode = qr
              
              // 触发完成事件
              this.$emit('complete', { success: true })
            } else {
              console.error('获取canvas节点失败')
              this.$emit('complete', { success: false, error: '获取canvas节点失败' })
            }
          })
        
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.generated = false
        this.$emit('complete', { success: false, error: error.message })
      }
    },
    
    // 点击事件
    handleClick() {
      this.$emit('click')
    },
    
    // 导出临时文件路径
    toTempFilePath(options = {}) {
      if (!this.generated) {
        console.warn('二维码尚未生成完成')
        return
      }
      
      const query = uni.createSelectorQuery().in(this)
      query.select(`#${this.canvasId}`)
        .fields({ node: true })
        .exec((res) => {
          if (res[0] && res[0].node) {
            const canvas = res[0].node
            
            uni.canvasToTempFilePath({
              canvas: canvas,
              fileType: options.fileType || 'png',
              quality: options.quality || 1,
              success: (result) => {
                console.log('导出成功:', result.tempFilePath)
                if (options.success) {
                  options.success(result)
                }
              },
              fail: (error) => {
                console.error('导出失败:', error)
                if (options.fail) {
                  options.fail(error)
                }
              }
            })
          }
        })
    },
    
    // 保存到相册
    save(options = {}) {
      this.toTempFilePath({
        success: (res) => {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              console.log('保存成功')
              if (options.success) {
                options.success()
              }
            },
            fail: (error) => {
              console.error('保存失败:', error)
              if (options.fail) {
                options.fail(error)
              }
            }
          })
        },
        fail: options.fail
      })
    }
  }
}
</script>

<style scoped>
.uqrcode-uni {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
